package com.hzt.agprosaleplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hzt.agprosaleplatform.common.CustomResponse;
import com.hzt.agprosaleplatform.entity.CategoryTree;
import com.hzt.agprosaleplatform.entity.Good;
import com.hzt.agprosaleplatform.entity.GoodsEvaluation;
import com.hzt.agprosaleplatform.entity.detailedGoods;
import com.hzt.agprosaleplatform.service.GoodsService;
import com.hzt.agprosaleplatform.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson2.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/goods")
@CrossOrigin(origins = "http://localhost:5173")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ShopService shopService;

    /**
     * 测试主页种类图片展示
     * @return
     */
    @GetMapping("/selectTest/category={category}")
    public String selectTopTen(@PathVariable String category) {
        System.out.println("category:"+category);

        List<Good> goodsList = goodsService.selectByCategory(category);
        System.out.println(goodsList);

        return JSON.toJSONString(goodsList);
    }

    /**
     * 主页分页查询展示商品
     * @param category
     * @return
     */
    @GetMapping("/pageForCategory/category")
    public String pageForCategory(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "12") Integer pageSize,
            @RequestParam String category) {
        IPage<Good> goodsPage = goodsService.PageForCategory(category, pageNum, pageSize);
        return JSON.toJSONString(goodsPage);
    }

    /**
     * 通过gid查询农产品详细信息
     * @param gid
     * @return
     */
    @GetMapping("/selectGoodsByGid/gid={gid}")
    public String selectGoodsByGid(@PathVariable Integer gid) {
        Good good = goodsService.selectGoodsByGId(gid);
        return JSON.toJSONString(good);
    }

    /**
     * 普通模糊查询
     * @param keyword title/category 标签/品类
     * @return json
     */
    @GetMapping("/searchGoods")
    public String searchGoods(@RequestParam(required = false) String keyword) {
        List<Good> goodsList = goodsService.searchGoods(keyword);
        return JSON.toJSONString(goodsList);
    }

    /**
     * 分页模糊查询
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @GetMapping("/searchGoods/page")
    public String PageForSearchGoods(
            @RequestParam(defaultValue = "1")Integer pageNum,
            @RequestParam(defaultValue = "12")Integer pageSize,
            @RequestParam(required = false) String keyword
    ){
        System.out.println("keyword:"+keyword);
        IPage<Good> pageResult = goodsService.searchGoodsPage(keyword, pageNum, pageSize);
        System.out.println(pageResult.getRecords());
        return JSON.toJSONString(pageResult);
    }

    @GetMapping("/{gid}/detail")
    public detailedGoods GoodsDetail(@PathVariable Integer gid) {
        return goodsService.selectDetailedGoodsByGId(gid);
    }

    @GetMapping("/tree")
    public CustomResponse getCategoryTree(){
        List<CategoryTree> categoryTree = goodsService.getCategoryTree();
        return new CustomResponse(200,"OK",categoryTree);
    }

    /**
     * 发布商品(允许多张照片)
     * @param goodsImages
     * @return
     */
    @PostMapping("/newGoods")
    public CustomResponse addNewGood(
            @RequestPart("good") String goodJson,
            @RequestPart("goodsImages") List<MultipartFile> goodsImages
    ) {
        try {
            Good good = JSON.parseObject(goodJson, Good.class);
            System.out.println(good);
            return goodsService.addNewGood(good, goodsImages);
        } catch (Exception e) {
            return new CustomResponse(500, "添加商品失败：" + e.getMessage(), null);
        }
    }

    /**
     * 调用图片识别AI
     * @param goodsImg
     * @return
     */
    @PostMapping("/identify")
    public CustomResponse identifyAI(@RequestPart("file") MultipartFile goodsImg) {
        try{
            String imgURL = goodsService.identifyImgApi(goodsImg);
            return new CustomResponse(200, "OK", imgURL);
        }catch (Exception e){
            return new CustomResponse(500,"图片识别异常，请稍后重试",null);
        }
    }

    /**
     * 根据ShopID获取商铺的商品
     * @param shopID
     * @return
     */
    @GetMapping()
    public CustomResponse GetShopGoodsByShopID(@RequestParam Integer shopID) {
        try{
            List<Good> goodList = shopService.selectShopGoodsByShopId(shopID);
            return new CustomResponse(200,"���取店铺商品成功",goodList);
        }catch (Exception e){
            return new CustomResponse(500,"服务出错了！",null);
        }
    }
    /**
     * 删除商品
     * @param gid
     * @return
     */
    @DeleteMapping("/deleteGoods")
    public CustomResponse deleteGood(@RequestParam Integer gid) {
        return goodsService.deleteGood(gid);
    }

    /**
     * 更新商品信息
     * @param goodJson
     * @param files
     * @Author pyw
     * @return
     * @throws IOException
     */
    //String goodJson
    @PostMapping("/updateGoods")
    public CustomResponse updateGoods(
            @RequestPart("goods") String goodJson,
            @RequestPart("files") List<MultipartFile> files) throws IOException {
        try{
            //将JSON转回Good实体类
            Good good = JSON.parseObject(goodJson, Good.class);
            return goodsService.updateGood(good,files);
        }catch (Exception e){
            return new CustomResponse(500,"更新商品信息失败",null);
        }
    }

    /**
     * 评价商品接口
     * @param evaluationJson
     * @return
     */
    @PostMapping("/evaluate")
    public CustomResponse evaluateProduct(@RequestPart("evaluation") String evaluationJson) {
        try {
            GoodsEvaluation evaluation = JSON.parseObject(evaluationJson, GoodsEvaluation.class);
            String result = goodsService.EvaluateProduct(evaluation);

            if ("评价成功".equals(result)) {
                return new CustomResponse(200, "评价成功", null);
            } else {
                return new CustomResponse(400, result, null);
            }
        } catch (Exception e) {
            log.error("评价商品失败: ", e);
            return new CustomResponse(500, "系统错误: " + e.getMessage(), null);
        }
    }

    /**
     * 获取商品评价
     * @param gid
     * @return
     */
    @GetMapping("/evaluation")
    public CustomResponse getProductEvaluation(@RequestParam Integer gid) {
        try {
            List<GoodsEvaluation> evaluations = goodsService.getProductEvaluate(gid);
            return new CustomResponse(200, "获取评价成功", evaluations);
        } catch (Exception e) {
            log.error("获取商品评价失败: ", e);
            return new CustomResponse(500, "获取评价失败", null);
        }
    }

}
